package com.gc.web.controller.api;

import com.alibaba.fastjson.JSONObject;
import com.gc.business.domain.CustomerInfo;
import com.gc.business.domain.MemoNote;
import com.gc.business.service.ICustomerInfoService;
import com.gc.business.service.IMemoNoteService;
import com.gc.common.constant.BusinessConstants;
import com.gc.common.constant.Constants;
import com.gc.common.utils.RegexUtils;
import com.gc.common.utils.StringUtils;
import com.gc.framework.web.base.ApiBaseController;
import com.gc.system.domain.SysUser;
import com.gc.system.service.ISysUserService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @title 公司客户相关api接口层
 * @Date 2020/12/01 15:41
 * @author hruiyan
 */
@CrossOrigin
@Controller
@RequestMapping("/api/customer")
public class ApiCustomerInfoController extends ApiBaseController {

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ICustomerInfoService customerInfoService;

    @Autowired
    private IMemoNoteService memoNoteService;

    @Autowired
    private ISysUserService userService;


    /**
     * 查询公司客户列表接口
     * @param pageNum
     * @param pageSize
     * @param token
     * @param customerName  查询条件：客户名称
     * @return
     */
    @GetMapping("/selectCustomerList")
    @ResponseBody
    public Map<String,Object> selectCustomerList(Integer pageNum,Integer pageSize,String token,String customerName){

        Long userId = getUserId(token);
        SysUser sysUser =
                sysUserService.selectUserById(userId);


        //查询用户角色组
        String roleString = sysUserService.selectUserRole(userId);

        CustomerInfo customerInfo = new CustomerInfo();
        customerInfo.setCustomerName(customerName);
        if(roleString.contains(BusinessConstants.KEEP_MANAGER)){

            //为维保经理
            customerInfo.setCompanyId(sysUser.getAttrId());
        }else{
            //其他人员
            customerInfo.setCompanyId(sysUser.getAttrId());
            customerInfo.setHeadUserId(userId);
        }
        startPage(pageNum,pageSize,"create_time DESC");
        List<CustomerInfo> customerInfoList = customerInfoService.list(customerInfo);

        for (CustomerInfo info : customerInfoList) {
            if(!info.getHeadUserId().equals(userId)){
                info.setIsMe(2); //别人添加，不可修改
            }
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("pageNum",pageNum);
        jsonObject.put("list",customerInfoList);
        jsonObject.put("total",new PageInfo<>(customerInfoList).getTotal());

        return success(jsonObject);
    }

    /**
     * 添加保存客户信息接口
     * @param customerInfo
     * @param token
     * @return
     */
    @PostMapping("/saveCustomerInfo")
    @ResponseBody
    public Map<String,Object> saveCustomerInfo(CustomerInfo customerInfo,String token){

        Long userId = getUserId(token);

        //手机号校验
        if(StringUtils.isNull(customerInfo.getPhoneNumber())){
            return error(Constants.UNVERIFY,"请填写手机号 ！");
        }
        if(!RegexUtils.isMobile(customerInfo.getPhoneNumber())){
            return error(Constants.UNVERIFY,"手机号格式有误 ！");
        }

        //客户名称校验
        if(StringUtils.isNull(customerInfo.getCustomerName())){
            return error(Constants.UNVERIFY,"请填写客户名称 ！");
        }
        //客户公司校验
        if(StringUtils.isNull(customerInfo.getCustomerCompany())){
            return error(Constants.UNVERIFY,"请填写客户公司 ！");
        }

        try {
            SysUser sysUser = sysUserService.selectUserById(userId);
            if(StringUtils.isNull(customerInfo.getCustomerId())){
                customerInfo.setHeadUserId(userId);
                customerInfo.setCompanyId(sysUser.getAttrId());
                customerInfo.setCreateBy(sysUser.getUserName());
                customerInfo.setCreateTime(new Date());
                customerInfoService.save(customerInfo);
            }else{
                customerInfo.setUpdateBy(sysUser.getUserName());
                customerInfo.setUpdateTime(new Date());
                customerInfo.setCreateBy(sysUser.getUserName());
                customerInfoService.updateById(customerInfo);
            }
        }catch (Exception e){
            e.printStackTrace();
            return error(Constants.UNVERIFY,"服务错误，请联系管理员 ！");
        }
        return success(customerInfo);
    }

    /**
     * 编辑保存客户信息接口
     * @param customerInfo
     * @param token
     * @return
     */
    @PostMapping("/updateCustomerInfo")
    @ResponseBody
    public Map<String,Object> updateCustomerInfo(CustomerInfo customerInfo,String token){

        if(StringUtils.isNull(customerInfo.getCustomerId())){
            return error(Constants.UNVERIFY,"缺少必传参数： id ！");
        }

        SysUser sysUser = sysUserService.selectUserById(getUserId(token));
        try {
            customerInfo.setUpdateBy(sysUser.getUserName());
            customerInfo.setUpdateTime(new Date());
            customerInfoService.updateById(customerInfo);
        }catch (Exception e){
            e.printStackTrace();
            return error(Constants.UNVERIFY,"服务错误，请联系管理员 ！");
        }
        return success(customerInfo);
    }

    /**
     * 查询客户信息接口
     * @param customerId
     * @return
     */
    @GetMapping("/selectCustomerById")
    @ResponseBody
    public Map<String,Object> selectCustomerById(Long customerId){
        if(StringUtils.isNull(customerId)){
            return error(Constants.UNVERIFY,"缺少必传参数： id ！");
        }
        return success(customerInfoService.getById(customerId));
    }

    /**
     * 查询销售列表数量
     * @param token
     * @return
     */
    @GetMapping("/querySalesHeadNums")
    @ResponseBody
    public Map<String,Object> querySalesHeadNums(String token){

        Long userId = getUserId(token);
        SysUser sysUser =
                sysUserService.selectUserById(userId);

        /**
         * 查询客户数量
         */
        List<JSONObject> mapList = new ArrayList<>();

        JSONObject objectByCustomer = new JSONObject();
        objectByCustomer.put("title","客户");
        //查询用户角色组
        String roleString = sysUserService.selectUserRole(userId);

        CustomerInfo customerInfo = new CustomerInfo();
        if(roleString.contains(BusinessConstants.KEEP_MANAGER)){
            //为维保经理
            customerInfo.setCompanyId(sysUser.getAttrId());
        }else{
            //其他人员
            customerInfo.setCompanyId(sysUser.getAttrId());
            customerInfo.setHeadUserId(userId);
        }
        objectByCustomer.put("num",customerInfoService.list(customerInfo).size());

        mapList.add(objectByCustomer);


        /**
         * 查询通讯录数量
         */
        JSONObject objectByUsers = new JSONObject();

        SysUser user = new SysUser();
        user.setAttrId(sysUser.getAttrId());
        objectByUsers.put("title","通讯录");
        objectByUsers.put("num",userService.selectUserList(user).size());

        mapList.add(objectByUsers);

        /**
         * 查询备忘录数量
         */
        JSONObject objectByMemo = new JSONObject();

        MemoNote memoNote = new MemoNote();
        memoNote.setUserId(userId);
        int numByMemo = memoNoteService.list(memoNote).size();

        objectByMemo.put("title","备忘录");
        objectByMemo.put("num",numByMemo);

        mapList.add(objectByMemo);

        return success(mapList);
    }


}
